//.filter-wrapper 更多按钮收起、或者展开
var $wrapper = $('.filter-wrapper'),
    $btn = $('.revision-btn-search', $wrapper);
$('a.more').on('click', function () {
    if ($wrapper.hasClass('open')) {
        $(this).html(
            '更多<i class="revision-icon-more"></i>'
        );
        $wrapper.removeClass('open').css({
            'height': 34
        });
        $btn.css({
            'bottom': '2px'
        });
    } else {
        $(this).html(
            '收起<i class="revision-icon-more active"></i>'
        );
        $wrapper.addClass('open').css({
            'height': $('ul', $wrapper).height()
        });
        $btn.css({
            'bottom': '4px'
        });
    }
});
window.onresize = function () {
    // select2
    if (document.body.clientWidth > 1660) {
        $('.filter-wrapper .select2.select2-container.select2-container--default').css('width', '220px');
    } else {
        $('.filter-wrapper .select2.select2-container.select2-container--default').css('width', '180px');
    }
};
//tab(弹出层需要单页面内写)
(function (pluginName) {
    $.fn[pluginName] = function (param) {
        var arr = [],
            len = this.length;
        for (var i = 0; i < len; i++) {
            var obj = new Tab(this[i], param);
            arr.push(obj);
        }
        return arr;
    }

    function Tab(elem, param) {
        var defaults = {
            tabEvent: 'click',
            elem: $(elem),
            curClass: 'current', // 当前选项的类名
            beforeTab: null, // 切换之前的回调
            fn: null // 切换(之后)回调
        };
        $.extend(this, defaults, param);
        this.init();
    }

    Tab.prototype = {
        init: function () {
            var _this = this;
            $('li', _this.elem.children('.tabs')).on(_this.tabEvent, function () {
                var $this = $(this),
                    index = 0,
                    oriIndex = -1; // 切换之前的索引
                if ($this.hasClass(_this.curClass)) return;
                index = $this.index();
                oriIndex = $('.tabs .' + _this.curClass, _this.elem).index();
                _this.openTab(index, oriIndex);
            });
        },
        openTab: function (index, oriIndex) {
            debugger;
            if (typeof this.beforeTab === 'function' && typeof oriIndex != 'undefined') {
                var flag = this.beforeTab(index, oriIndex);
                if (flag === false) {
                    return;
                }
            }
            $('li', this.elem.children('.tabs')).eq(index).addClass(this.curClass).siblings().removeClass(this.curClass);
            this.elem.children('.tab-cont').children('.tab-item').eq(index).removeClass('none').siblings().addClass('none');
            if (typeof this.fn === 'function') {
                this.fn(index);
            }
        }
    }
})('tab');

//表单序列化
var formSerialize = function (el) {
    //创建一个form
    var array = $('[name]', $(el)).serializeArray();
    //序列化data成 字面量
    var data = {};
    array.forEach(function (e) {
        data[e.name] = e.value;
    });
    return data;
}

var baseData = {
    rootUrl: "http://47.96.179.49:8080/",
    redirectUrl: "../../web/login/login.html",
    //遮罩加载条
    loading: false,
    //列表加载条
    listLoading: false,
    pageInit: true,
    token: 'bearer ',
    //分页
    pageObj: {
        dataTotal: 0,
        pageNumber: 1,
        pageSize: 10,
        dataNumber: 0
    },
    confirm: {
        show: false,
        styleMax: {
            width: '900px'
        },
        styleMin: {
            width: '500px'
        },
        addClass: 'scroll-modal',
        callBack: {
            type: Function
        },
        init: function () {
            $(this.$el).css('z-index', 10000)
        }
    },
    alert: {
        show: false,
        styleMax: {
            width: '900px'
        },
        styleMin: {
            width: '500px'
        },
        addClass: 'scroll-modal',
        func: {
            type: Function
        },
        init: function () {
            $(this.$el).css('z-index', 10000)
        }
    },
};
//获取基础数据方法(可放在localStrange)
var baseCommonFunction = {
    //url 地址 sendData数据 type:POST,GET  callBack:回调
    PageAajx: function (url, sendData, callBack) {
        var page = {
            pageNumber: vm.$get("pageObj") === undefined ? 1 : vm.$get("pageObj.pageNumber"),
            pageSize: vm.$get("pageObj") === undefined ? 10 : vm.$get("pageObj.pageSize")
        };
        var sendData = JSON.stringify($.extend(sendData, page));
        $.ajax({
            url: vm.rootUrl + url,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'post',
            data: sendData,
            headers: {
                Authorization: vm.token + localStorage.getItem("bearar ")
            },
            // beforeSend: beforeSend || function () {
            //     if (vm !== undefined) {
            //         vm.$set('listLoading', true);
            //         vm.$set('pageObj.dataTotal', 0);
            //         vm.$set('pageObj.pageNumber', 0);
            //         vm.$set('result.List', []);
            //         vm.$set('result.Summary', {});
            //     }
            // },
            success: function (data) {
                vm.$set('listLoading', false);
                if (data.status == 200 && data.data) {
                    vm.$set('result.List', data.data.models);
                    if (data.data.amount != undefined) {
                        vm.$set('result.Summary', data.data.amount);
                    }
                    vm.$set('pageObj.dataTotal', data.data.count);
                    vm.$set('pageObj.pageNumber', data.data.pageIndex);
                } else {
                    vm.$set('result.List', []);
                    vm.$set('result.Summary', {});
                    vm.$set('pageObj.dataTotal', 0);
                    vm.$set('pageObj.pageNumber', 0);
                    vm.Alert(data.Message == "" ? "查询失败，" : data.Message);
                }
                if (callBack != undefined && callBack != null) {
                    callBack(data);
                }
            },
            error: function (xhr, v) {
                if (xhr.status == 401 || xhr.status == 451 || xhr.status == 452 || xhr.status == 453) {
                    window.location.href = vm.redirectUrl;
                }
                vm.$set('result.List', []);
                vm.$set('result.Summary', {});
                vm.$set('result.Extra', {});
                vm.$set('listLoading', false);
            }
        });
    },
    //isAll 是否要返回全部树 0 全部 1部分（带权限）
    //isShowInvalidation 是否显示无效 underfind/0：显示全部 1：不显示无效
    //treeId 格式 "#xxxId"
    loadTree: function (isAll, isShowInvalidation, treeId) {
        //ajax请求数据格式
        var dataObj = [{
            "treePath": "/",
            "id": "300000",
            "text": "all",
            "value": "300000",
            "remain": "True",
            "ChildNodes": [{
                "treePath": "1",
                "hasChildren": true,
                "id": "6870",
                "text": "a",
                "value": "6870",
                "remain": "False",
                "ChildNodes": [{
                        "treePath": "2",
                        "hasChildren": true,
                        "id": "7124",
                        "text": "b",
                        "value": "7124",
                        "remain": "False"
                    },
                    {
                        "treePath": "2",
                        "hasChildren": true,
                        "id": "6982",
                        "text": "c",
                        "value": "6982",
                        "remain": "False",
                        "ChildNodes": [{
                            "treePath": "3",
                            "hasChildren": true,
                            "id": "7159",
                            "text": "dbc",
                            "value": "7159",
                            "remain": "False",
                            "ChildNodes": [{
                                    "treePath": "4",
                                    "hasChildren": true,
                                    "id": "8285",
                                    "text": "e",
                                    "value": "8285",
                                    "remain": "False"
                                },
                                {
                                    "treePath": "4",
                                    "hasChildren": true,
                                    "id": "8753",
                                    "text": "fa",
                                    "value": "8753",
                                    "remain": "False"
                                },
                                {
                                    "treePath": "4",
                                    "hasChildren": true,
                                    "id": "8872",
                                    "text": "g",
                                    "value": "8872",
                                    "remain": "False"
                                }
                            ]
                        }]
                    }
                ]
            }]
        }];
        if (dataObj) {
            var projTreeObj = $.fn.zTree.init($(treeId), {
                check: {
                    enable: true
                },
                data: {
                    key: {
                        name: 'text',
                        children: 'ChildNodes',
                        title: 'text'
                    }
                },
                callback: {
                    onCheck: function () {
                        vm.setCheckId(projTreeObj.getCheckedNodes(), "treeIds");
                    }
                }
            }, dataObj);
            projTreeObj.checkAllNodes(true);
            vm.setCheckId(projTreeObj.getCheckedNodes(), "treeIds");
            vm.treeIds.paramId = vm.treeIds.checkedId;
        }
    },
    //451  令牌必须以bearer 开始，包含空格！
    //452 令牌已过期！
    //453 长时间未操作，令牌已被收回！
    //401 认证未通过
    //IsAsy：同/异步 false同步
    RequestGetAajx: function (ajaxParam, callBack) {
        $.ajax({
            url: vm.rootUrl + ajaxParam.url,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'get',
            async: (ajaxParam.async != undefined ? ajaxParam.async : true),
            headers: {
                Authorization: vm.token + localStorage.getItem("bearar ")
            },
            success: function (data) {
                if (data.status == 200) {
                    callBack(data);
                }
            },
            error: function (xhr, statusText) {
                if (xhr.status == 401 || xhr.status == 451 || xhr.status == 452 || xhr.status == 453) {
                    window.location.href = vm.redirectUrl;
                }
                callBack(xhr, statusText);
            }
        });
    },
    RequestPostAajx: function (ajaxParam, callBack) {
        let head = {};
        if (ajaxParam.flg != 0) {
            head = {
                Authorization: vm.token + localStorage.getItem("bearar ")
            }
        }
        $.ajax({
            url: vm.rootUrl + ajaxParam.url,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'post',
            async: (ajaxParam.async != undefined ? ajaxParam.async : true),
            headers: head,
            data: JSON.stringify(ajaxParam.param),
            success: function (data) {
                if (data.status == 200) {
                    if (ajaxParam.flg == 0) {
                        localStorage.setItem("bearar ", data.data.accessToken);
                    }
                    callBack(data);
                }
            },
            error: function (xhr, statusText) {
                if (xhr.status == 401 || xhr.status == 451 || xhr.status == 452 || xhr.status == 453) {
                    window.location.href = vm.redirectUrl;
                }
                callBack(xhr, statusText);
            }
        });
    },
    //删除
    RequestDeleteAjax: function (ajaxParam, callBack) {
        let head = {};
        if (ajaxParam.flg != 0) {
            head = {
                Authorization: vm.token + localStorage.getItem("bearar ")
            }
        }
        $.ajax({
            url: vm.rootUrl + ajaxParam.url,
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'delete',
            async: (ajaxParam.async != undefined ? ajaxParam.async : true),
            headers: head,
            data: JSON.stringify(ajaxParam.param),
            success: function (data) {
                if (data.status == 200) {
                    if (ajaxParam.flg == 0) {
                        localStorage.setItem("bearar ", data.data.accessToken);
                    }
                    callBack(data);
                }
            },
            error: function (xhr, statusText) {
                if (xhr.status == 401 || xhr.status == 451 || xhr.status == 452 || xhr.status == 453) {
                    window.location.href = vm.redirectUrl;
                }
                callBack(xhr, statusText);
            }
        });
    },
    //alert警告窗
    Alert: function (msg, func) {
        $("#confirmInvoiceTxt").removeAttr("style");
        vm.$set('alert.Msg', '');
        vm.$set('alert.Msg', msg);
        if (func === undefined) {
            vm.$set('alert.func', function () {
                vm.$set('alert.show', false);
            });
        } else {
            vm.$set('alert.func', function () {
                vm.$set('alert.show', false);
                func();
            });
        }
        vm.$set('alert.show', true);
        vm.$nextTick(function () {
            var height = $("#confirmInvoiceTxt").height();
            if (height > 350) {
                $("#confirmInvoiceTxt").attr("style", "height:350px;overflow-y: scroll;");
            }
        });
    },
    //confirm确认框
    Confirm: function (msg, callback, cancelcallBack) {
        vm.$set('confirm.Msg', '');
        vm.$set('confirm.Msg', msg);
        //确认
        if (callback !== undefined && typeof callback === "function") {
            var callbackNew = function (e) {
                vm.$set('confirm.show', false);
                callback(e);
            };
            vm.$set('confirm.callBack', callbackNew);
        } else {
            var callbackNew1 = function () {
                vm.$refs.confirm.show = false;
            };
            vm.$set('confirm.callBack', callbackNew1);
        }
        //取消
        if (cancelcallBack !== undefined && typeof callback === "function") {
            var callbackNew2 = function () {
                vm.$set('confirm.show', false);
                cancelcallBack();
            };
            vm.$set('confirm.cancelcallBack', callbackNew2);
        } else {
            var callbackNew3 = function () {
                vm.$refs.confirm.show = false;
            };
            vm.$set('confirm.cancelcallBack', callbackNew3);
        }
        vm.$set('confirm.show', true);
    },
};
//参数格式化
var mvcParamMatch = (function () {
    //格式转换
    var MvcParameterAdaptive = {};
    //验证是否为数组
    MvcParameterAdaptive.isArray = Function.isArray || function (o) {
        return typeof o === "object" &&
            Object.prototype.toString.call(o) === "[object Array]";
    };
    //将数组转换为对象
    MvcParameterAdaptive.convertArrayToObject = function ( /*数组名*/ arrName, /*待转换的数组*/ array, /*转换后存放的对象，不用输入*/ saveOjb) {
        var obj = saveOjb || {};

        function func(name, arr) {
            for (var i in arr) {
                if (!MvcParameterAdaptive.isArray(arr[i]) && typeof arr[i] === "object") {
                    for (var j in arr[i]) {
                        if (MvcParameterAdaptive.isArray(arr[i][j])) {
                            func(name + "[" + i + "]." + j, arr[i][j]);
                        } else if (typeof arr[i][j] === "object") {
                            MvcParameterAdaptive.convertObject(name + "[" + i + "]." + j + ".", arr[i][j], obj);
                        } else {
                            obj[name + "[" + i + "]." + j] = arr[i][j];
                        }
                    }
                } else {
                    obj[name + "[" + i + "]"] = arr[i];
                }
            }
        }

        func(arrName, array);

        return obj;
    };
    //转换对象
    MvcParameterAdaptive.convertObject = function ( /*对象名*/ objName, /*待转换的对象*/ turnObj, /*转换后存放的对象，不用输入*/ saveOjb) {
        var obj = saveOjb || {};

        function func(name, tobj) {
            for (var i in tobj) {
                if (MvcParameterAdaptive.isArray(tobj[i])) {
                    MvcParameterAdaptive.convertArrayToObject(name + i, tobj[i], obj); //将数组所属的对象名称也传递过去
                } else if (typeof tobj[i] === "object") {
                    func(name + i + ".", tobj[i]);
                } else {
                    obj[name + i] = tobj[i];
                }
            }
        }
        func(objName, turnObj);
        return obj;
    };
    return function (json, arrName) {

        arrName = arrName || "";
        if (typeof json !== "object") throw new Error("请传入json对象");
        if (MvcParameterAdaptive.isArray(json) && !arrName) throw new Error("请指定数组名，对应Action中数组参数名称！");

        if (MvcParameterAdaptive.isArray(json)) {
            return MvcParameterAdaptive.convertArrayToObject(arrName, json);
        }
        return MvcParameterAdaptive.convertObject("", json);
    };
})();
//返回大写金额，包括数字金额
Vue.filter('moneyCapital', function (currencyDigits) {
    var maximumNumber = 99999999999.99;
    var cnZero = "零";
    var cnOne = "壹";
    var cnTwo = "贰";
    var cnThree = "叁";
    var cnFour = "肆";
    var cnFive = "伍";
    var cnSix = "陆";
    var cnSeven = "柒";
    var cnEight = "捌";
    var cnNine = "玖";
    var cnTen = "拾";
    var cnHundred = "佰";
    var cnThousand = "仟";
    var cnTenThousand = "万";
    var cnHundredMillion = "亿";
    var cnDollar = "元";
    var cnTenCent = "角";
    var cnCent = "分";
    var cnInteger = "整";
    var integral; // Represent integral part of digit number.
    var decimal; // Represent decimal part of digit number.
    var outputCharacters; // The output result.
    var parts;
    var digits, radices, bigRadices, decimals;
    var zeroCount;
    var i, p, d;
    var quotient, modulus;
    // Validate input string:
    currencyDigits = currencyDigits == undefined ? "0" : currencyDigits.toString();
    if (currencyDigits.match(/[^,.\d]/) != null) {
        //alert("Invalid characters in the input string!");
        return "";
    }
    if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
        return "";
    }
    // Normalize the format of input digits:
    currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
    currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning.
    if (Number(currencyDigits) > maximumNumber) {
        //alert("Too large a number to convert!");
        return "";
    }
    parts = currencyDigits.split(".");
    if (parts.length > 1) {
        integral = parts[0];
        decimal = parts[1];
        decimal = decimal.substr(0, 2);
    } else {
        integral = parts[0];
        decimal = "";
    }
    digits = new Array(cnZero, cnOne, cnTwo, cnThree, cnFour, cnFive, cnSix, cnSeven, cnEight, cnNine);
    radices = new Array("", cnTen, cnHundred, cnThousand);
    bigRadices = new Array("", cnTenThousand, cnHundredMillion);
    decimals = new Array(cnTenCent, cnCent);
    outputCharacters = "";
    if (Number(integral) > 0) {
        zeroCount = 0;
        for (i = 0; i < integral.length; i++) {
            p = integral.length - i - 1;
            d = integral.substr(i, 1);
            quotient = p / 4;
            modulus = p % 4;
            if (d === "0") {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    outputCharacters += digits[0];
                }
                zeroCount = 0;
                outputCharacters += digits[Number(d)] + radices[modulus];
            }
            if (modulus === 0 && zeroCount < 4) {
                outputCharacters += bigRadices[quotient];
            }
        }
        outputCharacters += cnDollar;
    }
    if (decimal !== "") {
        for (i = 0; i < decimal.length; i++) {
            d = decimal.substr(i, 1);
            if (d !== "0") {
                outputCharacters += digits[Number(d)] + decimals[i];
            }
        }
    }
    if (outputCharacters === "") {
        outputCharacters = cnZero + cnDollar;
    }
    if (decimal === "") {
        outputCharacters += cnInteger;
    }
    if (decimal === "00") {
        outputCharacters += cnInteger;
    }
    return currencyDigits == "" ? "0.00" : (currencyDigits == ".00" ? "0.00" : currencyDigits) + " | " + outputCharacters;
});
Vue.filter('money', {
    read: function (val) {
        if (typeof val === 'undefined') {
            return '0.00';
        }
        var money = parseFloat(val).toFixed(2).toString();
        newStr = "",
            count = 0;
        for (var i = money.indexOf(".") - 1; i >= 0; i--) {
            if (count % 3 == 0 && count != 0) {
                newStr = money.charAt(i) + "," + newStr;
            } else {
                newStr = money.charAt(i) + newStr;
            }
            count++;
        }
        //newStr 为整数部分，将小数部分拼上去
        money = newStr + money.substr(money.indexOf("."));
        return money;
    },
    write: function (val) {
        val = parseFloat(val);
        return isNaN(val) ? 0 : parseFloat(val.toFixed(2));
    }
});